package com.javahash.spring.service;

import com.javahash.spring.Model.MongoExchangeModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

//TODO @Service
//rename to RateSetrvice
//move to service package
//@Autowire ExcengeRatesService and use as object
@Service
public class MongoExchangeRates {


    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    APIExchangeRates apiExchangeRates;

    private final static Logger logger = Logger.getLogger(MongoExchangeRates.class.getName());



    Query query = new Query();
    Query lastDocumentQuery = query.with(new Sort(Sort.Direction.DESC, "lastModifiedDate"));


    public void saveApiExchangeRatesToDB() {

        String json = apiExchangeRates.getExchangeRatesJson();
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SS");
        //get current date time with Date()
        Date date = new Date();
        String dateString = dateFormat.format(date);
        MongoExchangeModel mongoExchangeModel = new MongoExchangeModel(dateString, json);
        mongoTemplate.save(mongoExchangeModel);

    }

    public String getLatestRates() {
        String latestRates = "";

        //Get Exchange Rates from DB
        try {
            latestRates = mongoTemplate.findOne(lastDocumentQuery, MongoExchangeModel.class).getCurrencies();


        } catch (Exception e) {

            logger.log(Level.WARNING, e.toString(),e);
        }

        //Get Exchange Rates from API , then write them to DB

        if (latestRates.isEmpty()) {

            try {

                MongoExchangeRates mongoExchangeRates = new MongoExchangeRates();
                mongoExchangeRates.saveApiExchangeRatesToDB();
                latestRates = mongoTemplate.findOne(lastDocumentQuery, MongoExchangeModel.class).getCurrencies();

            } catch (Exception e) {
                logger.log(Level.SEVERE,e.toString(),e);
            }
        }


        //If DB is not available , get Exchange Rates from API directly
        if (latestRates.isEmpty()) {

            try {

                latestRates = apiExchangeRates.getExchangeRatesJson();

            } catch (Exception e) {
                logger.log(Level.SEVERE,e.toString(),e);
            }
        }



        return latestRates;


    }


}
